package com.ygg.interceptor;

import com.ygg.exception.YyghException;
import com.ygg.helper.HttpRequestHelper;
import com.ygg.model.hosp.HospitalSet;
import com.ygg.result.ResultCodeEnum;
import com.ygg.service.HospitalSetService;
import com.ygg.utils.MD5;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *
 */
@Component
public class ApiDepartmentInterceptor implements HandlerInterceptor {

    @Resource
    HospitalSetService hospitalSetService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = HttpRequestHelper.switchMap(parameterMap);
        //获取签名
        String sign = map.get("sign").toString();
        //获取医院编码
        String hoscode = map.get("hoscode").toString();
        if (hoscode == null) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //查询数据库看签名是否一致
        HospitalSet one = hospitalSetService.query().eq("hoscode", hoscode).select("sign_key").one();
        String encrypt = MD5.encrypt(one.getSignKey());
        if (!sign.equals(encrypt)) {
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
